import axios from 'axios';
import qs from 'qs';
import { Message } from 'element-ui';
import Vue from 'vue';

const R = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
});

//取消axios请求
var CancelToken = axios.CancelToken;
Vue.prototype._cancels_ = [];

/**
 * 请求拦截器
 */
R.interceptors.request.use((_) => {
  const config = _;
  const IS_GET = config.method === 'get';
  const data = (IS_GET ? config.params : config.data) || {};

  config.headers['Authorization'] = localStorage.getItem('token');
  config.cancelToken = new CancelToken((c) => {
    Vue.prototype._cancels_.push(c);
  });

  if (IS_GET) {
    data['_t'] = Date.now();
    config.params = data;
  } else {
    if (config.headers['Content-Type'] == 'application/json') {
      config.data = data;
    } else {
      config.data = qs.stringify(data);
    }
  }

  return {
    ...config,
  };
});

/**
 * 响应拦截器
 */
R.interceptors.response.use(
  (response) => Promise.resolve(response.data.data ? response.data.data : response.data),
  (error) => {
    if (error.response && error.response.data) {
      if (error.response.config.url !== '/auth/info') {
        Message({
          type: 'error',
          message: error.response.data.message,
        });
      }
    }
    return Promise.reject(error.response);
  },
);

export default R;
